package com.tianfei.crowd.controller;

import com.tianfei.crowd.api.MySQLRemoteService;
import com.tianfei.crowd.config.OSSProperties;
import com.tianfei.crowd.constant.CrowdConstants;
import com.tianfei.crowd.entity.vo.*;
import com.tianfei.crowd.utils.CrowdUtil;
import com.tianfei.crowd.utils.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * Project-Consumer 端的 controller
 *
 * 用来收集 页面 所有表单提交的数据
 *
 * @author: Herz
 * @date: 2021/8/4 22:23
 */
@Controller
public class ProjectConsumerController {

    @Autowired
    private OSSProperties ossProperties;

    @Autowired
    private MySQLRemoteService mySQLRemoteService;



    @RequestMapping("/show/project/detail/{projectId}")
    public String showDetailProject(
            @PathVariable("projectId") Integer projectId,
            ModelMap modelMap){

        ResultEntity<DetailProjectVO> resultEntity = mySQLRemoteService.getDetailProjectVORemote(projectId);

        String result = resultEntity.getResult();

        if (ResultEntity.SUCCESS.equals(result)){

            DetailProjectVO data = resultEntity.getData();

            modelMap.addAttribute("detailProjectVO", data);
        }

        return "project-detail";
    }




    @RequestMapping("/create/confirm")
    public String saveConfirm(MemberConfirmInfoVO memberConfirmInfoVO, HttpSession session, ModelMap modelMap) {

        // 1、从 Session域里获取 ProjectVO对象
        ProjectVO projectVO = (ProjectVO) session.getAttribute(CrowdConstants.ATTR_PROJECTVO_MESSAGE);

        // 2、判断ProjectVO是否为null
        if (projectVO == null) {

            throw new RuntimeException(CrowdConstants.MESSAGE_TEMPORARY_PROJECT_MISSING);
        }

        // 3、将确认信息 存入到ProjectVO对象中
        projectVO.setMemberConfirmInfoVO(memberConfirmInfoVO);

        // 4、从 Session 域中获取登录的用户
        MemberLoginVO memberLoginVO = (MemberLoginVO) session.getAttribute(CrowdConstants.MESSAGE_ATTR_MEMBER);

        Integer memberId = memberLoginVO.getId();

        // 5、将所有信息已经封装好的 ProjectVO 存入 MySQL数据库中
        // 远程声明式调用
        ResultEntity<String> saveProjectRemoteResultEntity = mySQLRemoteService.saveProjectRemote(projectVO, memberId);

        // 6、判断是否保存成功
        if (ResultEntity.FAILED.equals(saveProjectRemoteResultEntity.getResult())) {

            modelMap.addAttribute(CrowdConstants.ATTR_NAME_MESSAGE, saveProjectRemoteResultEntity.getMessage());

            return "project3-confirm";
        }

        // 7、保存成功，将 Session 中临时存储的 ProjectVO 对象删除
        session.removeAttribute(CrowdConstants.ATTR_PROJECTVO_MESSAGE);

        // 8、保存成功跳转到最终完成页面
        return "redirect:http://localhost/project/new/crowd/to/project/success/page";
    }


    @ResponseBody
    @RequestMapping("/create/save/return")
    public ResultEntity<String> saveReturn(ReturnVO returnVO, HttpSession session) {

        try {
            // 1、从 Session 域里取出ProjectVO
            ProjectVO projectVO = (ProjectVO) session.getAttribute(CrowdConstants.ATTR_PROJECTVO_MESSAGE);

            // 2、判断取出的 ProjectVO是否为空
            if (projectVO == null) {

                return ResultEntity.failed(CrowdConstants.MESSAGE_TEMPORARY_PROJECT_MISSING);
            }

            // 3、从 projectVO 中取出存储汇报信息的集合
            List<ReturnVO> returnVOList = projectVO.getReturnVOList();

            // 4、判断取出的集合是否可用
            if (returnVOList == null || returnVOList.size() == 0) {

                // 5、不可用时则初始化
                returnVOList = new ArrayList<>();

                // 6、再将初始化后的集合存入ProjectVO 对象中
                projectVO.setReturnVOList(returnVOList);
            }

            // 7、将页面手机的回报信息存入集合中
            returnVOList.add(returnVO);

            // 8、将存入了 回报信息集合 的 ProjectVO 对象存入 Session域中
            session.setAttribute(CrowdConstants.ATTR_PROJECTVO_MESSAGE, projectVO);

            // 9、所有操作完成返回成功
            return ResultEntity.successWithOutData();
        } catch (Exception e) {
            e.printStackTrace();

            return ResultEntity.failed(e.getMessage());
        }
    }


    @ResponseBody
    @RequestMapping("/create/upload/return/picture")
    public ResultEntity<String> uploadReturnPic(

            // 用来保存浏览器上传的图片文件
            @RequestParam("returnPicture") MultipartFile returnPicture) throws IOException {

        // 执行上传
        ResultEntity<String> uploadReturnPicResultEntity = CrowdUtil.uploadFileToOss(
                ossProperties.getEndPoint(),
                ossProperties.getAccessKeyId(),
                ossProperties.getAccessKeySecret(),
                returnPicture.getInputStream(),
                ossProperties.getBucketName(),
                ossProperties.getBucketDomain(),
                returnPicture.getOriginalFilename());

        // 将上传结果返回
        return uploadReturnPicResultEntity;
    }


    @RequestMapping("/create/project/information")
    public String saveProjectInformation(

            // 用来存储 除上传图片以外的一部分其他普通信息
            ProjectVO projectVO,

            // 接收上传的头图
            MultipartFile headerPicture,

            // 接收上传的详情图片
            List<MultipartFile> detailPictureList,

            // 用来临时的存储 ProjectVO
            HttpSession session,

            ModelMap modelMap) throws IOException {


        // 一、完成上传头图
        // 1、判断用户是否上传头图
        boolean headerPictureEmpty = headerPicture.isEmpty();

        if (headerPictureEmpty) {
            // 头图为空
            modelMap.addAttribute(CrowdConstants.ATTR_NAME_MESSAGE, CrowdConstants.MESSAGE_HEADER_PIC_UPLOAD_EMPTY);

            return "project1-message";
        }

        // 2、如果用户确实上传了图片，则执行上传
        ResultEntity<String> uploadFileResultEntity = CrowdUtil.uploadFileToOss(
                ossProperties.getEndPoint(),
                ossProperties.getAccessKeyId(),
                ossProperties.getAccessKeySecret(),
                headerPicture.getInputStream(),
                ossProperties.getBucketName(),
                ossProperties.getBucketDomain(),
                headerPicture.getOriginalFilename());


        String result = uploadFileResultEntity.getResult();

        // 3、判断头图是否上传成功
        if (ResultEntity.SUCCESS.equals(result)) {

            // 4、从返回的数据中获取头图的访问路径
            String headerPicturePath = uploadFileResultEntity.getData();

            // 5、存入 ProjectVO对象
            projectVO.setHeaderPicturePath(headerPicturePath);

        } else {

            // 头图上传失败
            // 6、在modelMap中存入错误提示信息
            modelMap.addAttribute(CrowdConstants.ATTR_NAME_MESSAGE, CrowdConstants.MESSAGE_HEADER_PIC_UPLOAD_FAILED);

            // 7、返回发起项目表单页面
            return "project1-message";
        }


        // 二、详情图片上传
        // 创建一个集合来存放上传的详情图片的访问地址
        List<String> detailPicturePathList = new ArrayList<>();

        // 0、判断集合是否可用
        if (detailPictureList.size() == 0 || detailPictureList.isEmpty()) {

            modelMap.addAttribute(CrowdConstants.ATTR_NAME_MESSAGE, CrowdConstants.MESSAGE_DETAILS_UPLOAD_EMPTY);

            return "project1-message";
        }

        // 1、遍历详情图片集合
        for (MultipartFile detailPicture : detailPictureList) {

            // 2、判断每一个图片是否可用
            if (detailPicture.isEmpty()) {

                modelMap.addAttribute(CrowdConstants.ATTR_NAME_MESSAGE, CrowdConstants.MESSAGE_DETAIL_EMPTY);

                return "project1-message";
            }

            // 3、执行上传
            ResultEntity<String> detailUploadResultEntity = CrowdUtil.uploadFileToOss(
                    ossProperties.getEndPoint(),
                    ossProperties.getAccessKeyId(),
                    ossProperties.getAccessKeySecret(),
                    detailPicture.getInputStream(),
                    ossProperties.getBucketName(),
                    ossProperties.getBucketDomain(),
                    detailPicture.getOriginalFilename());

            String detailUploadResultEntityResult = detailUploadResultEntity.getResult();

            // 4、判断每一详情图片是否上传成功
            if (ResultEntity.SUCCESS.equals(detailUploadResultEntityResult)) {

                // 5、获取每一个详情图片的访问地址，并存入访问地址集合中
                String detailPicturePath = detailUploadResultEntity.getData();

                detailPicturePathList.add(detailPicturePath);

            } else {

                modelMap.addAttribute(CrowdConstants.ATTR_NAME_MESSAGE, CrowdConstants.MESSAGE_UPLOAD_DETAILS_FAILED);

                return "project1-message";
            }
        }

        // 三、存入数据
        // 1、将刚刚访问详情图片的访问地址集合存入ProjectVO对象中
        projectVO.setDetailPicturePathList(detailPicturePathList);

        // 2、将 projectVO 存入到session域中
        session.setAttribute(CrowdConstants.ATTR_PROJECTVO_MESSAGE, projectVO);

        // 3、重定向到下一个页面
        return "redirect:http://localhost/project/new/crowd/to/project/return/page";
    }

}
